package com.samxcode.leetcode;

/**
 * The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this:
 * P   A   H   N
 * A P L S I I G
 * Y   I   R
 * (you may want to display this pattern in a fixed font for better legibility)
 * 
 * And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this
 * conversion given a number of rows: string convert(string text, int nRows);
 * convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
 * 
 * @author Sam
 *
 */
public class ZigzagConversion {

    public static void main(String[] args) {
        System.out.println(convert("PA", 1));
    }


    public static String convert(String s, int nRows) {
        if (nRows == 1) {
            return s;
        }
        char[] arr = s.toCharArray();
        char[] zcArr = new char[arr.length];
        int i = 0;
        for (int m = 0; m < nRows; m++) {
            for (int j = m; j < zcArr.length; j += 2 * (nRows - 1)) {
                if (m == 0 || m == nRows - 1) {
                    zcArr[i++] = arr[j];
                } else {
                    zcArr[i++] = arr[j];
                    int n = j + (nRows - m - 1) * 2;
                    if (n < zcArr.length) {
                        zcArr[i++] = arr[n];
                    }                    
                }
            }
        }
        return String.valueOf(zcArr);
    }
}
